﻿@page "/account/login"
@using ELS.Services
@inject IAccountService AccountService
@inject NavigationManager NavigationManager
@inject ISnackbar Snackbar

<MudGrid Justify="Justify.Center" Style="min-height: 80vh; align-content: center;">
	<MudItem xs="12" md="12" sm="12">
		<MudText Typo="Typo.h4" Align="Align.Center" Class="mb-8">登录系统</MudText>
		<div class="card-body">
			<MudGrid Justify="Justify.Center">
				<MudItem xs="10" md="4" sm="8">
					<MudPaper Class="pa-8">
						<MudForm @ref="@form" Model="@model">
							<MudTextField Label="用户名" @bind-Value="model.Username" Variant="Variant.Outlined" Required="true" RequiredError="用户名不能为空!" Class="mb-4" />
							<MudTextField Label="密码" @bind-Value="model.Password" Variant="Variant.Outlined" Required="true" InputType="InputType.Password" RequiredError="密码不能为空!" />
						</MudForm>
					</MudPaper>
				</MudItem>

				<MudFlexBreak />
				<MudItem xs="10" md="4" sm="8">
					<MudPaper Class="pa-8" Style="text-align: center;">
						<MudButton ButtonType="ButtonType.Submit" Color="Color.Primary" OnClick="@(async () => await OnValidSubmit())" Variant="Variant.Filled">
							登录
						</MudButton>
						<MudLink Href="account/register" Class="ml-4">注册</MudLink>
					</MudPaper>
				</MudItem>
			</MudGrid>
		</div>
	</MudItem>
</MudGrid>

@code {
	private Models.Account.Login model = new Models.Account.Login();
	private bool loading;
	MudForm form;

	private async Task OnValidSubmit()
	{
		try
		{
			await form.Validate();
			if (!form.IsValid)
			{
				return;
			}
			await AccountService.Login(model);

			NavigationManager.NavigateTo("");
			Snackbar.Add("登录成功", Severity.Success);
		}
		catch (Exception ex)
		{
			Snackbar.Add(ex.Message, Severity.Error);
			loading = false;
			StateHasChanged();
		}
	}

	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		await AccountService.Initialize();
		if (AccountService.User != null)
		{
			NavigationManager.NavigateTo("");
		}
		await base.OnAfterRenderAsync(firstRender);
	}
}
